const { ipcRenderer } = require('electron');

// 仅通过IPC获取端口，不设置默认值
let apiPort = null;

function fetchData(url, retries = 2, timeout = 10000) {
  return new Promise((resolve, reject) => {
    const attemptRequest = (attempt) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url);
      xhr.timeout = timeout;

      xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            resolve(JSON.parse(xhr.responseText));
          } catch (e) {
            if (attempt < retries) {
              console.warn(`JSON解析失败，重试 ${attempt + 1}/${retries + 1}`);
              setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
            } else {
              reject(new Error('Invalid JSON'));
            }
          }
        } else {
          if (attempt < retries) {
            console.warn(`HTTP ${xhr.status}，重试 ${attempt + 1}/${retries + 1}`);
            setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
          } else {
            reject(new Error('HTTP ' + xhr.status));
          }
        }
      };

      xhr.onerror = () => {
        if (attempt < retries) {
          console.warn(`网络错误，重试 ${attempt + 1}/${retries + 1}`);
          setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
        } else {
          reject(new Error('Network error'));
        }
      };

      xhr.ontimeout = () => {
        if (attempt < retries) {
          console.warn(`请求超时，重试 ${attempt + 1}/${retries + 1}`);
          setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
        } else {
          reject(new Error('Request timeout'));
        }
      };

      xhr.send();
    };

    attemptRequest(0);
  });
}

// 新增：统一API地址生成函数（兼容IPv4/IPv6）
function getApiUrl(endpoint) {
  // 优先使用IPv4地址，避免解析问题
  const ENDPOINTS = [
    `http://127.0.0.1:${apiPort}`,
    `http://[::1]:${apiPort}`
  ];
  const baseUrl = ENDPOINTS[0];
  return baseUrl + endpoint;
}

function formatNumber(num) {
  if (num >= 10000) return (num / 10000).toFixed(1) + '万';
  return (num || 0).toString();
}

// 专门用于获取API端口的函数
async function fetchApiPort() {
  return new Promise((resolve, reject) => {
    if (!ipcRenderer) {
      reject(new Error('ipcRenderer不可用'));
      return;
    }

    ipcRenderer.invoke('get-settings')
      .then(overlaySettings => {
        const port = overlaySettings.apiPort;
        if (port && !isNaN(port) && port > 0 && port <= 65535) {
          apiPort = port;
          console.log('成功通过IPC获取API端口:', apiPort);
          resolve();
        } else {
          reject(new Error(`获取到无效端口: ${port}`));
        }
      })
      .catch(err => {
        reject(new Error(`IPC通信失败: ${err.message}`));
      });
  });
}

async function renderAllPlayers() {
  const grid = document.getElementById('playersGrid');
  try {
    // 强制检查端口是否已通过IPC获取
    if (!apiPort) {
      grid.innerHTML = '<div class="loading">端口未通过IPC正确配置</div>';
      return;
    }

    // 修改：使用getApiUrl生成请求地址
    const resp = await fetchData(getApiUrl('/api/data'));
    const userMap = resp.user || {};
    const players = Object.keys(userMap).map(uid => ({ uid, ...userMap[uid] }));

    players.sort((a, b) => (b.total_damage?.total || 0) - (a.total_damage?.total || 0));
    const max = players.length > 0 ? (players[0].total_damage?.total || 1) : 1;
    let html = '';
    players.forEach(p => {
      const dmg = p.total_damage?.total || 0;
      const heal = p.total_healing?.total || 0;
      const taken = p.taken_damage || 0;
      const percent = Math.round((dmg / max) * 100);
      html += `
        <div class="card" onclick="showPlayerSkills(${p.uid})" style="cursor: pointer;">
          <div class="header">
            <div class="name">${p.nickname || p.name || ('玩家_' + p.uid)}</div>
            <div class="profession">${p.profession || '未知'}</div>
          </div>
          <div class="bar"><div class="fill" style="width:${percent}%"></div></div>
          <div class="stats">
            <div class="stat"><span class="label">总伤害</span><span class="value">${formatNumber(dmg)}</span></div>
            <div class="stat"><span class="label">总治疗</span><span class="value">${formatNumber(heal)}</span></div>
            <div class="stat"><span class="label">总承伤</span><span class="value">${formatNumber(taken)}</span></div>
          </div>
        </div>`;
    });
    grid.innerHTML = html || '<div class="loading"> 暂无数据</div>';
  } catch (e) {
    grid.innerHTML = `<div class="loading">加载失败: ${e.message}</div>`;
  }
}

// 显示玩家技能详情
async function showPlayerSkills(uid) {
  try {
    // 强制检查端口
    if (!apiPort) {
      alert('端口未通过IPC正确配置，无法加载技能详情');
      return;
    }

    console.log('Loading skills for player:', uid);
    // 修改：使用getApiUrl生成请求地址
    const resp = await fetchData(getApiUrl(`/api/skill-stats/${uid}?sort=damage`));

    if (resp.code === 0 && resp.data && resp.data.length > 0) {
      // 统一为主入口风格的技能详情
      showSkillModalUnified(uid, resp.data);
    } else {
      alert('该玩家暂无技能数据');
    }
  } catch (error) {
    console.error('加载技能数据失败:', error);
    alert('加载技能数据失败: ' + error.message);
  }
}

// 统一样式技能详情（黑灰白配色方案）
function showSkillModalUnified(uid, skillData) {
  const modal = document.createElement('div');
  modal.className = 'modal';
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
  `;

  const content = document.createElement('div');
  content.className = 'modal-content';
  content.style.cssText = `
    background: rgba(20, 20, 20, 0.95);
    border-radius: 8px;
    padding: 16px;
    max-width: 800px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
    border: 2px solid rgba(128, 128, 128, 0.3);
    backdrop-filter: blur(8px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
  `;

  const header = document.createElement('div');
  header.className = 'modal-header';
  header.style.cssText = `
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 2px solid rgba(128, 128, 128, 0.3);
  `;
  header.innerHTML = `
    <h3 style="color: #f0f0f0; margin: 0; font-size: 18px; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);">玩家 ${uid} 的技能详情</h3>
    <button onclick="this.closest('.modal').remove()" style="background: rgba(60, 60, 60, 0.8); color: #f0f0f0; border: 1px solid rgba(128, 128, 128, 0.4); padding: 6px 10px; border-radius: 4px; cursor: pointer; font-size: 14px;">✖️</button>
  `;
  content.appendChild(header);

  const body = document.createElement('div');
  body.className = 'modal-body';
  body.style.cssText = `
    max-height: 60vh;
    overflow-y: auto;
    padding: 0;
  `;

  const list = document.createElement('div');
  list.className = 'skill-details-content';
  list.style.cssText = `
    padding: 4px;
  `;

  // 分别计算总伤害和总治疗量
  const totalDamage = skillData.reduce((sum, skill) => {
    // 混合技能和伤害技能都算在伤害里
    return sum + (skill.skill_type !== 'healing' ? (skill.total_damage || 0) : 0);
  }, 0);
  
  const totalHealing = skillData.reduce((sum, skill) => {
    // 只有纯治疗技能算在治疗里
    return sum + (skill.skill_type === 'healing' ? (skill.total_damage || 0) : 0);
  }, 0);

  let html = '';

  // 添加技能类型图例
  html += `
    <div style="display: flex; gap: 12px; margin-bottom: 12px; padding: 8px; background: rgba(255, 255, 255, 0.05); border-radius: 6px; border: 1px solid rgba(255, 255, 255, 0.1);">
      <span style="font-size: 11px; padding: 3px 8px; border-radius: 12px; font-weight: bold; opacity: 0.8; background: rgba(192, 13, 7, 0.2); color: #ff6b6b;">🗡️ 伤害</span>
      <span style="font-size: 11px; padding: 3px 8px; border-radius: 12px; font-weight: bold; opacity: 0.8; background: rgba(46, 204, 113, 0.2); color: #2ecc71;">💚 治疗</span>
      <span style="font-size: 11px; padding: 3px 8px; border-radius: 12px; font-weight: bold; opacity: 0.8; background: rgba(149, 165, 166, 0.2); color: #95a5a6;">🛡️ 承伤</span>
      <span style="font-size: 11px; padding: 3px 8px; border-radius: 12px; font-weight: bold; opacity: 0.8; background: rgba(243, 156, 18, 0.2); color: #f39c12;">⚡ 复合</span>
    </div>
  `;

  // 添加技能占比可视化图表
  if (skillData && skillData.length > 0) {
    // 按伤害排序
    const sortedSkills = [...skillData].sort((a, b) => (b.total_damage || 0) - (a.total_damage || 0));

    html += `<div style="margin: 8px 0; padding: 8px; background: rgba(0, 0, 0, 0.3); border-radius: 6px; border: 1px solid rgba(128, 128, 128, 0.3); backdrop-filter: blur(4px);">`;
    sortedSkills.forEach((skill, index) => { // 显示所有技能
      const skillType = skill.skill_type || 'damage';
      const skillValue = skill.total_damage || 0;
      
      // 根据技能类型计算百分比
      let percentage, barWidth;
      if (skillType === 'healing') {
        // 治疗技能：按总治疗量计算百分比
        percentage = totalHealing > 0 ? ((skillValue / totalHealing) * 100).toFixed(1) : '0.0';
        barWidth = totalHealing > 0 ? ((skillValue / totalHealing) * 100) : 0;
      } else {
        // 伤害技能和混合技能：按总伤害计算百分比
        percentage = totalDamage > 0 ? ((skillValue / totalDamage) * 100).toFixed(1) : '0.0';
        barWidth = totalDamage > 0 ? ((skillValue / totalDamage) * 100) : 0;
      }
      
      // 根据技能类型确定颜色和图标
      let borderColor = 'rgba(192, 192, 192, 0.4)';
      let barGradient = 'linear-gradient(90deg, rgba(235, 40, 40, 0.8), rgb(235, 40, 40))';
      let typeIcon = '🗡️';
      let valueLabel = '伤害';
      
      switch (skillType) {
        case 'healing':
          borderColor = 'rgba(46, 204, 113, 0.6)';
          barGradient = 'linear-gradient(90deg, rgba(46, 204, 113, 0.8), rgb(46, 204, 113))';
          typeIcon = '💚';
          valueLabel = '治疗';
          break;
        case 'taken':
          borderColor = 'rgba(149, 165, 166, 0.6)';
          barGradient = 'linear-gradient(90deg, rgba(149, 165, 166, 0.8), rgb(149, 165, 166))';
          typeIcon = '🛡️';
          valueLabel = '承伤';
          break;
        case 'mixed':
          borderColor = 'rgba(243, 156, 18, 0.6)';
          barGradient = 'linear-gradient(90deg, rgba(243, 156, 18, 0.8), rgb(243, 156, 18))';
          typeIcon = '⚡';
          valueLabel = '复合';
          break;
        default:
          borderColor = 'rgba(192, 13, 7, 0.6)';
          barGradient = 'linear-gradient(90deg, rgba(192, 13, 7, 0.8), rgb(192, 13, 7))';
          typeIcon = '🗡️';
          valueLabel = '伤害';
          break;
      }

      const critRate = skill.crit_rate || '0.0';
      const critCount = skill.crit_count || 0;
      const luckyRate = skill.lucky_rate || '0.0';

      html += `
        <div style="margin-bottom: 6px; padding: 6px 8px; background: rgba(40, 40, 40, 0.6); border-radius: 4px; border-left: 2px solid ${borderColor}; transition: all 0.2s ease; position: relative;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
            <div style="font-weight: 600; color: #f0f0f0; font-size: 12px; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8); display: flex; align-items: center; gap: 6px;">
              <span style="font-size: 12px;">${typeIcon}</span>
              <span>${skill.skill_name}</span>
            </div>
            <div style="font-weight: 700; color: #ffffff; font-size: 11px; background: rgba(0, 0, 0, 0.6); padding: 2px 6px; border-radius: 4px; border: 1px solid rgba(128, 128, 128, 0.4); text-shadow: 0 1px 1px rgba(0, 0, 0, 0.8);">${percentage}%</div>
          </div>
          <div style="height: 6px; background: rgba(0, 0, 0, 0.4); border-radius: 3px; overflow: hidden; margin-bottom: 4px; border: 1px solid rgba(64, 64, 64, 0.6); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.6); position: relative;">
            <div style="height: 100%; border-radius: 3px; transition: width 0.3s ease; background: ${barGradient}; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4); width: ${barWidth}%;"></div>
            ${parseFloat(luckyRate) > 0 ? `<div style="position: absolute; right: 4px; top: 50%; transform: translateY(-50%); font-size: 8px; color: #ffd700; text-shadow: 0 0 2px rgba(255, 215, 0, 0.5);">✨${luckyRate}%</div>` : ''}
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center; font-size: 10px; color: rgba(200, 200, 200, 0.9);">
            <span style="font-weight: 600; color: ${skillType === 'healing' ? '#2ecc71' : '#e0e0e0'}; font-size: 11px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.6);" title="${valueLabel}: ${formatNumber(skill.total_damage || 0)}">${formatNumber(skill.total_damage || 0)}</span>
            <span style="color: rgba(180, 180, 180, 0.9); font-size: 10px; background: rgba(0, 0, 0, 0.4); padding: 1px 4px; border-radius: 3px; border: 1px solid rgba(96, 96, 96, 0.6);">${skill.count || 0}次</span>
            <span style="color: rgba(180, 180, 180, 0.9); font-size: 10px; background: rgba(0, 0, 0, 0.4); padding: 1px 4px; border-radius: 3px; border: 1px solid rgba(228, 134, 134, 0.6);" title="暴击: ${critCount}次 / 暴击率: ${critRate}%">
              暴击率 ${critRate}%
              ${parseFloat(critRate) > 0 ? '<span style="margin-left: 2px; font-size: 8px;">💥</span>' : ''}
            </span>
            <span style="color: rgba(180, 180, 180, 0.9); font-size: 10px; background: rgba(0, 0, 0, 0.4); padding: 1px 4px; border-radius: 3px; border: 1px solid rgba(228, 134, 134, 0.6);">幸运率 ${luckyRate}%</span>
          </div>
          ${parseFloat(critRate) > 30 ? '<div style="position: absolute; top: -2px; right: -2px; font-size: 8px; padding: 1px 4px; border-radius: 6px; font-weight: bold; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5); background: linear-gradient(45deg, #ff4757, #ff3742); color: white;">高暴击</div>' : ''}
          ${parseFloat(luckyRate) > 10 ? '<div style="position: absolute; top: -2px; right: -2px; font-size: 8px; padding: 1px 4px; border-radius: 6px; font-weight: bold; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5); background: linear-gradient(45deg, #ffd700, #ffed4a); color: #333;">幸运王</div>' : ''}
        </div>
      `;
    });
    html += `</div>`;
  }

  list.innerHTML = html || '<div class="skill-empty">暂无技能数据</div>';
  body.appendChild(list);
  content.appendChild(body);
  modal.appendChild(content);
  document.body.appendChild(modal);
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', async () => {
  console.log('All players page loaded');

  // 强制通过IPC获取端口，不设置默认值
  try {
    await fetchApiPort();
    console.log('端口初始化完成:', apiPort);
    // 端口获取成功后渲染玩家列表
    renderAllPlayers();
  } catch (error) {
    const grid = document.getElementById('playersGrid');
    grid.innerHTML = `<div class="loading">端口配置失败: ${error.message}</div>`;
    console.error('端口获取失败:', error);
  }
});

// 全局函数，供HTML调用
window.showPlayerSkills = showPlayerSkills;